package part23swingdemo.com.etc.ui;

import java.awt.EventQueue;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JLabel;

import part23swingdemo.com.etc.pojo.Userinfo;
import part23swingdemo.com.etc.service.UserinfoService;
import part23swingdemo.com.etc.service.UserinfoServiceImpl;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class MainJFrame {

	private JFrame frame;
	private JTable table;
	
	private UserinfoService userinfoService = new UserinfoServiceImpl();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainJFrame window = new MainJFrame(new Userinfo(1, "xx", "123456", 18));
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainJFrame(Userinfo userinfo) {
		initialize(userinfo);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize(Userinfo userinfo) {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 窗口显示在页面中间
		frame.setLocationRelativeTo(null);
		// 窗口不允许调整大小
		frame.setResizable(false);
		// 设置窗口名称
		frame.setTitle("主页面");
		frame.getContentPane().setLayout(null);
		
		JLabel label = new JLabel("欢迎你：" + userinfo.getUsername());
		label.setBounds(10, 10, 135, 15);
		frame.getContentPane().add(label);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(47, 54, 325, 176);
		frame.getContentPane().add(scrollPane);
		
		table = new JTable();
		
		// 1 填充数据
		// 1.1 调用业务层,获取所有用户列表
		List<Userinfo> allUsers = userinfoService.getAllUsers();
		
		Object[][] data = new Object[allUsers.size()][4];// 行数应该是数据库查询出来的用户总数
		// 1.2 集合的数据 填充到 二维数组中
		
		for (int i = 0; i < allUsers.size(); i++) {
			// 集合中每一个对象的
			Userinfo user = allUsers.get(i); 
			data[i][0] = user.getUserId();
			data[i][1] = user.getUsername();
			data[i][2] = user.getPassword();
			data[i][3] = user.getAge();
		}
		// 2填充列
		String[] cols = {"用户编号","用户名","密码","年龄"};
		
		table.setModel(new DefaultTableModel(
			data,
			cols
		));
		scrollPane.setViewportView(table);
		// 显示界面
		frame.setVisible(true);
	}
}
